package com.pine.common.redis.lock;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;

/**
 * redis锁key生成函数
 *
 * @author pine manage
 * @since 2024-08-09
 */
public class RedisLockJsonKeyFunction implements Function<Object, String> {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private static final Lock LOCK = new ReentrantLock();

    /**
     * Applies this function to the given argument.
     *
     * @param object the function argument
     * @return the function result
     */
    @Override
    public String apply(Object object) {
        return serializeToJson(object);
    }


    /**
     * 序列化对象为json
     *
     * @param object 对象
     * @return json
     */
    private static String serializeToJson(Object object) {
        try {
            LOCK.lock();
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            LOCK.unlock();
        }
    }
}
